﻿namespace Api.Controllers;

/// <summary>
/// 登录日志
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
[Authorize]
public class LoginLogController(IConfiguration configuration, ILoginLogBLL loginLogBLL, IOperationLogBLL operationLogBLL) : BaseController(operationLogBLL)
{
    private readonly IConfiguration _configuration = configuration;
    private readonly ILoginLogBLL _loginLogBLL = loginLogBLL;

    #region 登录日志列表分页
    /// <summary>
    /// 登录日志列表分页
    /// </summary>
    /// <param name="pageQuery">分页查询条件</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel<List<LoginLog>>> QueryPageListAsync([FromBody] LoginLogPageQueryRM pageQuery)
    {
        RefAsync<int> total = 0;
        var list = await _loginLogBLL.QueryPageListAsync(pageQuery, total);
        var ret = new ResultModel<List<LoginLog>>
        {
            data = list,
            count = total,
        };
        return ret;
    }
    #endregion

    #region 导出登录日志
    /// <summary>
    /// 导出登录日志
    /// </summary>
    /// <param name="exportQuery">分页查询条件</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> ExportLoginLogAsync([FromBody] ExportLoginLogPageQueryRM exportQuery)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel();
            var taskmodel = new ExcelTaskModel
            {
                task = Util.CreateGUID(),
                type = 2,
                status = 1
            };
            excelTasks.Add(taskmodel.task, taskmodel);

            string path = "";
            try
            {
                #region 任务
                var list = new List<LoginLog>();
                var pageQuery = MapperHelper.Mapper<LoginLogPageQueryRM, ExportLoginLogPageQueryRM>(exportQuery);
                pageQuery.PageIndex = 1;
                pageQuery.PageSize = 50;
                RefAsync<int> total = 0;
                var temp = await _loginLogBLL.QueryPageListAsync(pageQuery, total);
                while (temp.Count > 0)
                {
                    list.AddRange(temp);
                    pageQuery.PageIndex += 1;
                    temp = await _loginLogBLL.QueryPageListAsync(pageQuery, total);
                }

                var data = new Dictionary<string, List<string[]>>();
                var rows = new List<string[]>
                {
                    new string[] { "用户名", "姓名", "用户角色", "IP地址", "登录时间", "登录时长（分钟）" }
                };

                foreach (var item in list)
                {
                    string[] row =
                    [
                        item.Account,
                        item.Name,
                        item.RoleName,
                        item.Ip,
                        item.LoginTime.ToYMDHMS(),
                        item.Duration.ToString(),
                    ];
                    rows.Add(row);
                }
                data.Add("登录日志", rows);

                string fileDir = Path.Combine(AppContext.BaseDirectory, "wwwroot", "excel");
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                string filepath = Path.Combine(fileDir, "登录日志.xlsx");

                NPOIHelper.ExportToExcel(data, filepath);
                path = "/excel/登录日志.xlsx";
                #endregion
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
            taskmodel.status = 2;
            taskmodel.path = path;
            excelTasks[taskmodel.task] = taskmodel;

            result.code = 1;
            result.data = taskmodel.task;
            return result;
        }, new AddOperationLogInput { Content = $"导出登录日志" });

    }
    #endregion

    #region 登录日志更新登录时长
    /// <summary>
    /// 登录日志更新登录时长
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ResultModel> UpdateLoginDuration(int userId, int duration)
    {
        var res = new ResultModel();
        var loginLogList = await _loginLogBLL.GetListAsync(x => x.UserId == userId);
        if (loginLogList != null && loginLogList.Any())
        {
            var loginLog = loginLogList.OrderByDescending(x => x.LoginTime).FirstOrDefault();
            if (loginLog != null)
            {
                loginLog.Duration += duration;
                res.data = await _loginLogBLL.UpdateAsync(loginLog);
            }
        }
        res.code = 1;
        return res;
    }
    #endregion

    #region 登录日志定期清理接口
    /// <summary>
    /// 登录日志定期清理接口
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public async Task<ResultModel> LogDataClearJob()
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var res = new ResultModel();
            var logReserveDays = Convert.ToInt32(_configuration["LoginLogReserveDays"]);
            DateTime earliestReserveDate = DateTime.Now.Date.AddDays(-logReserveDays + 1);
            var earliestLog = (await _loginLogBLL.GetListAsync()).OrderBy(x => x.Id).FirstOrDefault();
            if (earliestLog == null || earliestLog.LoginTime > earliestReserveDate)
            {
                res.code = -1;
                return res;
            }
            DateTime start = earliestLog.LoginTime.Date;
            var deleteRes = new List<LoginLog>();
            while (start < earliestReserveDate)
            {
                var list = await _loginLogBLL.GetListAsync(l => l.LoginTime >= start && l.LoginTime < start.AddDays(1));
                if (list == null || list.Count == 0)
                {
                    start = start.AddDays(1);
                    continue;
                }
                deleteRes.AddRange(list);
                start = start.AddDays(1);
            }
            //删除30天以前的日志
            await _loginLogBLL.DeleteAsync(deleteRes);
            res.code = 1;
            return res;
        });
    }
    #endregion
}